<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Community } from '@/api/community/type';
import { getCommunityInfo, getCommunityMember, checkWhetherToJoin, joinCommunity, leaveCommunity } from '@/api/community';
import { useUserStore } from '@/store/user';
import { showDialog, showNotify } from 'vant';
import Tabs from './components/Tabs.vue';

// 路由和状态
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 社区信息
const communityId = ref('');
const community = ref<Community>({} as Community);
const memberCount = ref(0);
const isJoined = ref(false);
const isOwner = ref(false);
const loading = ref(true);

// 加载社区信息
const loadCommunityData = async () => {
  try {
    loading.value = true;
    
    const id = route.query.id as string;
    if (!id) {
      showNotify({
        type: 'danger',
        message: '社区ID不存在',
        position: 'top'
      });
      router.back();
      return;
    }
    
    communityId.value = id;
    
    // 并行加载社区信息
    const [infoRes, memberRes, joinRes] = await Promise.all([
      getCommunityInfo(id),
      getCommunityMember(id),
      checkWhetherToJoin(id)
    ]);
    
    community.value = infoRes.data as Community;
    memberCount.value = memberRes.data as number;
    isJoined.value = joinRes.data as boolean;
    
    // 检查当前用户是否是创建者
    isOwner.value = community.value.creator === userStore.getId;
    
  } catch (error) {
    console.error('加载社区信息失败:', error);
    showNotify({
      type: 'danger',
      message: '加载社区信息失败',
      position: 'top'
    });
  } finally {
    loading.value = false;
  }
};

// 加入社区
const handleJoinCommunity = async () => {
  try {
    const userId = userStore.getId;
    if (!userId) {
      showNotify({
        type: 'warning',
        message: '请先登录',
        position: 'top'
      });
      return;
    }
    
    await joinCommunity(communityId.value, userId);
    isJoined.value = true;
    memberCount.value++;
    
    showNotify({
      type: 'success',
      message: `已成功加入"${community.value.name}"`,
      position: 'top'
    });
  } catch (error) {
    console.error('加入社区失败:', error);
    showNotify({
      type: 'danger',
      message: '加入社区失败',
      position: 'top'
    });
  }
};

// 离开社区
const handleLeaveCommunity = async () => {
  try {
    await showDialog({
      title: '离开社区',
      message: `确定要离开"${community.value.name}"吗？`,
      showCancelButton: true
    });
    
    const userId = userStore.getId;
    await leaveCommunity(communityId.value, userId);
    isJoined.value = false;
    memberCount.value = Math.max(0, memberCount.value - 1);
    
    showNotify({
      type: 'success',
      message: '已成功离开社区',
      position: 'top'
    });
  } catch (error) {
    if (error !== 'cancel') {
      console.error('离开社区失败:', error);
      showNotify({
        type: 'danger',
        message: '离开社区失败',
        position: 'top'
      });
    }
  }
};

// 跳转到社区设置
const navigateToSettings = () => {
  router.push({
    name: "CommunitySetting",
    query: {
      'id': communityId.value
    }
  });
};

// 发布文章
const publishArticle = () => {
  router.push({
    name: 'CommunityArticleEdit',
    query: {
      "communityId": communityId.value
    }
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};

onMounted(() => {
  loadCommunityData();
});
</script>

<template>
  <div class="community-home">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="36" vertical>加载中...</van-loading>
    </div>
    
    <template v-else>
      <!-- 社区封面 -->
      <div class="community-header">
        <div class="back-button" @click="goBack">
          <van-icon name="arrow-left" />
        </div>
        
        <div class="community-banner" :style="{backgroundImage: `linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.3)), url(${community.url})`}">
          <div class="community-info">
            <div class="community-avatar-container">
              <van-image
                round
                width="80"
                height="80"
                :src="community.url"
                class="community-avatar"
                fit="cover"
              />
            </div>
            
            <div class="community-details">
              <h1 class="community-name">{{ community.name }}</h1>
              <div class="community-stats">
                <span class="member-count">{{ memberCount }} {{ community.title || '成员' }}</span>
              </div>
              <p v-if="community.description" class="community-description">
                {{ community.description }}
              </p>
            </div>
            
            <div class="community-actions">
              <template v-if="isOwner">
                <van-button
                  type="primary"
                  size="small"
                  icon="setting-o"
                  @click="navigateToSettings"
                >
                  管理社区
                </van-button>
              </template>
              <template v-else>
                <van-button
                  v-if="isJoined"
                  type="default"
                  size="small"
                  icon="minus"
                  @click="handleLeaveCommunity"
                >
                  已加入
                </van-button>
                <van-button
                  v-else
                  type="primary"
                  size="small"
                  icon="plus"
                  @click="handleJoinCommunity"
                >
                  加入社区
                </van-button>
              </template>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 文章内容标签页 -->
      <div class="community-content">
        <Tabs v-model="communityId" />
      </div>
      
      <!-- 发布按钮 -->
      <div class="publish-button">
        <van-button
          type="primary"
          icon="edit"
          round
          @click="publishArticle"
        >
          发帖
        </van-button>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.community-home {
  height: calc(100vh - 108px);
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  position: relative;
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
  }
  
  .community-header {
    position: relative;
    
    .back-button {
      position: absolute;
      top: 16px;
      left: 16px;
      z-index: 10;
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.8);
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background-color: rgba(255, 255, 255, 0.95);
        transform: scale(1.05);
      }
      
      .van-icon {
        font-size: 20px;
        color: #323233;
      }
    }
    
    .community-banner {
      height: 250px;
      background-size: cover;
      background-position: center;
      position: relative;
      display: flex;
      align-items: flex-end;
      
      .community-info {
        width: 100%;
        padding: 40px 24px 24px;
        display: flex;
        align-items: flex-end;
        background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
        color: white;
        
        .community-avatar-container {
          margin-right: 20px;
          
          .community-avatar {
            border: 3px solid white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
          }
        }
        
        .community-details {
          flex: 1;
          
          .community-name {
            font-size: 24px;
            font-weight: 600;
            margin: 0 0 8px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
          }
          
          .community-stats {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            
            .member-count {
              font-size: 14px;
              opacity: 0.9;
            }
          }
          
          .community-description {
            margin: 0;
            font-size: 14px;
            opacity: 0.9;
            max-width: 600px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
        }
        
        .community-actions {
          flex-shrink: 0;
        }
      }
    }
  }
  
  .community-content {
    flex: 1;
    overflow: hidden;
    background-color: white;
    border-radius: 8px 8px 0 0;
    margin-top: -20px;
    position: relative;
    z-index: 2;
    box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
  }
  
  .publish-button {
    position: fixed;
    right: 24px;
    bottom: 24px;
    z-index: 10;
    
    .van-button {
      width: 96px;
      height: 44px;
      font-size: 16px;
      box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
    }
  }
}
</style>